let express = require('express');
let mysql = require('./db');

let router = express.Router();

//查询所有分类
router.get('/category', (req, res) => {
    mysql.query(`select distinct * from category`, (state, data) => {
        if (state) {
            mysql.query(`select count(*) as total from category;`, (state1, total) => {
                if (state1) {
                    res.send({
                        code: 200,
                        msg: '请求成功',
                        total: total[0].total,
                        data
                    })
                } else {
                    res.send({
                        code: 400,
                        msg: '请求错误',
                        data
                    })
                }
            })
        } else {
            res.send({
                code: 400,
                msg: '请求错误',
                data
            })
        }
    })
})

//添加分类
router.post('/addCategory', function (req, res) {
    let { category } = req.body

    mysql.query(`insert into category(id,category) values(Null,'${category}');`, (state, data) => {
        if (state) {
            res.send({
                code: 200,
                msg: '分类添加成功',
                data
            })

        } else {
            res.send({
                code: 400,
                msg: '分类添加失败',
                data
            })
        }
    })
})

//删除分类
router.post('/delCategory', (req, res) => {
    let { id } = req.body;
    mysql.query(`delete from category where id='${id}';`, (state, data) => {
        if (state) {
            res.send({
                code: 200,
                msg: '删除数据成功'
            })
        } else {
            res.send({
                code: 400,
                msg: '删除数据失败'
            })
        }
    })
})

//修改分类
router.post('/updateCategory', function (req, res) {
    let { category, id } = req.body

    mysql.query(`update category set category='${category}' where id='${id}';`, (state, data) => {
        if (state) {
            res.send({
                code: 200,
                msg: '分类修改成功',
                data
            })

        } else {
            res.send({
                code: 400,
                msg: '分类修改失败',
                data
            })
        }
    })
})

//根据id查询指定数据
router.get('/category/:id', (req, res) => {
    let { id } = req.query
    mysql.query(`select * from category where id='${id}';`, (state, data) => {
        if (state) {
            res.send({
                code: 200,
                msg: '请求成功',
                data
            })
        } else {
            res.send({
                code: 400,
                msg: '请求错误',
                data
            })
        }
    })
})


module.exports = router